from time import sleep
import pyperclip

from playwright.sync_api import sync_playwright, Page

from api.api_db import up_date_drcs_status
from api.models import DRCS
from common.config import public_data
from .web_comm import get_token, select_option, excute_js, add_review_doc, add_attachment
from .project_info import project_dic, person_info, get_channel_info


def create_drcs(drcs_model: DRCS):
    channel_code = drcs_model.file_channel
    cc = drcs_model.cc
    title = drcs_model.title
    doc_dic = drcs_model.doc_json
    sys_attch: str = drcs_model.sys_attachment
    check_person = drcs_model.checker
    approve_person = drcs_model.approver

    new_drcs_url = r"http://aed.cnpdc.com/AED/Flow/DRCS/AED_DRCS_Edit.aspx?modi=add"

    if not public_data.Token:
        public_data.Token = get_token()

    if not public_data.Token:
        return False

    new_drcs_url += "&" + public_data.Token

    # channel_info = get_channel_info(channel_code)
    prj_code = drcs_model.project
    prj_name = project_dic[prj_code]
    factory_code = drcs_model.receiver_code

    with sync_playwright() as p:
        brower = p.chromium.launch(headless=False)
        page = brower.new_page()
        page.goto(new_drcs_url)
        url = page.url
        if r"https://uap.cgnpc.com.cn/" in url:
            try:
                page.wait_for_selector('//*[@id="drcs"]', timeout=60000)
            except Exception as e:
                print("获取验证超时")
                return
        alert_selector = "body > div.panel.window.panel-htop.messager-window > div.dialog-button.messager-button > a"

        base_info(page)  # 基础信息
        set_project(page, prj_code, prj_name)  # 设置项目
        alert_click(page, alert_selector)
        set_sender(page)  # 设置发送方
        alert_click(page, alert_selector)
        set_review(page, factory_code)  # 接收方
        set_title(page, channel_code, title)  # 设置标题等信息
        set_cc(page, cc)  # 抄送
        set_roler(page, check_person, approve_person)  # 设置审核和批准
        save_drcs(page)  # 保存
        drcs_model.url = page.url
        up_date_drcs_status(drcs_model.id,1)
        add_attachment(page, sys_attch)  # 添加附件
        drcs_model.url = page.url
        save_drcs(page)
        add_review_doc(page, channel_code)  # 添加文件
        # add_comments(page, doc_dic)  # 添加审查意见
        save_drcs(page)
        up_date_drcs_status(drcs_model.id,2)


def base_info(page: Page):
    id_select_secret = "ctl00_ContentPlaceHolder1_AED_DRCS_Edit1_DDL_Doc_SecClass"  # m密级选择
    select_company_id = "ctl00_ContentPlaceHolder1_AED_DRCS_Edit1_DDL_Bas_COMP_CODE"  # 所属公司选择
    select_language_id = "ctl00_ContentPlaceHolder1_AED_DRCS_Edit1_DDL_Bas_Language"  # 语种选择
    select_file_template_id = "stFileTemplate"  # 信函模板选择

    select_option(page, id_select_secret, "无密级")
    select_option(page, select_company_id, "工程公司")
    select_option(page, select_language_id, "中文")
    select_option(page, select_file_template_id, "设计审查单")


def set_project(page: Page, prj_code, prj_name):
    execute_str = f'updatePrjCodeDelegate("{prj_code}", "{prj_name}");'
    excute_js(page, execute_str)


def set_sender(page: Page):
    execute_str = 'updateFromInformation("GENS", "中广核工程有限公司", "中广核工程有限公司", "", "");'
    excute_js(page, execute_str)

    input_sender_name_id: str = '#ctl00_ContentPlaceHolder1_AED_DRCS_Edit1_fromTo_TB_FromCodeText'
    page.fill(input_sender_name_id, person_info["sender_srt"])


def set_review(page: Page, factory_code):
    btn_receiver_open_id: str = '#addJieShouFang'
    page.click(btn_receiver_open_id)
    receiver_iframe_id = '#frmDialogOpenSelectFromToCode'
    txt_receiver_id = "#txtKey"
    page.frame_locator(receiver_iframe_id).locator(txt_receiver_id).fill(factory_code)
    page.frame_locator(receiver_iframe_id).get_by_text("查询").click()
    '//*[@id="datagrid-row-r1-2-0"]/td[3]/div'
    page.frame_locator(receiver_iframe_id).locator("#datagrid-row-r1-2-0").click()
    text = page.frame_locator(receiver_iframe_id).locator('//*[@id="datagrid-row-r1-2-0"]/td[3]/div').inner_text()
    print(text)
    while text.strip() != factory_code:
        sleep(0.1)
        text = page.frame_locator(receiver_iframe_id).locator('//*[@id="datagrid-row-r1-2-0"]/td[3]/div').inner_text()
        print(text)
    page.locator('//div[@class="dialog-button"]/a//span[contains(text(),"保存")]').click()


def set_title(page: Page, channel_code, title):
    # 答复函通道号
    input_replied_channel_code_id = "#ctl00_ContentPlaceHolder1_AED_DRCS_Edit1_TB_Otr_TransmitRef"  # 文件通道号输入
    page.fill(input_replied_channel_code_id, channel_code)

    # 标题和审查意见
    input_title_id = "#ctl00_ContentPlaceHolder1_AED_DRCS_Edit1_Bas_Name__txt1"  # 标题输入
    if not title:
        title = f"传递单{channel_code}所提交文件的审查意见"
    page.fill(input_title_id, title)

    input_main_common_id = "#ctl00_ContentPlaceHolder1_AED_DRCS_Edit1_Bas_Remark"  # 审核意见输入
    page.fill(input_main_common_id, "详见详细意见。")


def set_cc(page: Page, cc: str):
    if cc:
        btn_inner_cc_xpath = '//input[@title="选择内部抄送"]'  # 内部抄送选择——打开一个frame
        frame_inner_cc_id = "#frmDialogOpenSelectCC"
        input_frame_cc_group_id = "#ctl00_ContentPlaceHolder1_TB_FFZ"  # 抄送的Frame id
        btn_inner_cc_save_xpath = '//div[@id="OpenSelectCC"]/following-sibling::*/a[1]'
        page.locator(btn_inner_cc_xpath).click()
        # page.frame_locator(frame_inner_cc_id).locator('//*[@id="aspnetForm"]/div[3]/div[2]/table/tbody/tr[2]/td/input').click()
        page.frame_locator(frame_inner_cc_id).locator(input_frame_cc_group_id).fill(cc)
        page.locator(btn_inner_cc_save_xpath).click()


def set_roler(driver: Page, check_person: str, approve_person: str):
    input_checker_id = "#shr_txt1"  # 审核人选择
    input_approver_id = "#pzr_txt1"  # 批准人选择
    div_checker_list_xpath = '//*[@id="shr_frm1"]/div/div'  # 审核人清单xpath
    div_approver_list_xpath = '//*[@id="pzr_frm1"]/div/div'  # 批准人清单xpath

    # 人员选择

    if check_person and approve_person:
        # 选择审批模式 为并行预设
        driver.get_by_label("并行预设").click()
        # driver.locator("#newSpMode$0$2").click()
        get_person(driver, input_checker_id, check_person, div_checker_list_xpath)
        get_person(driver, input_approver_id, approve_person, div_approver_list_xpath)

    else:
        driver.locator("#newSpMode$0$1").click()  # 串行审查    


# 添加人员
def get_person(driver: Page, input_person_code_id, person, div_person_list_xpath):
    person_code = person.strip()[:7]
    driver.locator(input_person_code_id).fill(person_code)
    count = 10
    while count > 1:
        els = driver.locator(div_person_list_xpath).all()
        count = len(els)
    driver.locator(input_person_code_id).click()
    driver.locator(div_person_list_xpath + "[1]").click()


# 保存DRCS
def save_drcs(driver: Page):
    btn_save_id = '#ctl00_ContentPlaceHolder1_BtnSave'
    driver.locator(btn_save_id).click()
    alert_click(driver, '//*[@id="dvSystemAlertbtn_0"]')
    sleep(0.5)

    btn_save_confirm_xpath = '//div[@class="dialog-button messager-button"]/a'
    driver.locator(btn_save_confirm_xpath).click()

    print("保存成功")


def alert_click(page: Page, loctor_str):
    alert_ = page.locator(loctor_str)
    if alert_.count():
        alert_.click()


# 添加附件


# uf
def add_comments(driver: Page, doc_dic: dict):
    driver.get_by_role("link", name="文件清单").click()
    els_path = '//tr[contains(@id,"datagrid-row-r1-2-")]'
    els = driver.locator(els_path).all()
    print(len(els))
    doc_list = doc_dic.keys()
    for el in els:
        tr_id = el.get_attribute("id")
        print(tr_id)
        code_xpath = f'//tr[@id="{tr_id}"]/td[@field="code"]//a'
        # code_el = driver.locator(code_xpath)
        document_code = driver.text_content(code_xpath)
        print(document_code)
        if document_code.strip() in doc_list:
            tr_id = el.get_attribute("id")
            doc_info = doc_dic[document_code]
            doc_result = doc_info["result"]
            doc_comment = doc_info["comment"]
            el_get_result_el_xpath = f'//tr[@id="{tr_id}"]//td[@field="fileresult"]'
            driver.locator(el_get_result_el_xpath).click()

            file_result_el_xpath = f'//tr[@id="{tr_id}"]//td[@field="fileresult"]//*[contains(@id,"easyui_textbox_input")]'
            driver.locator(file_result_el_xpath).fill(doc_result)

            # 审查意见
            file_opinion_el_xpath = f'//tr[@id="{tr_id}"]/td[@field="fileopinion"]//*[contains(@id,"_easyui_textbox_input")] '
            opinion_el_xpath = f'//tr[@id="{tr_id}"]//td[@field="fileopinion"]'
            driver.locator(opinion_el_xpath).click()
            pyperclip.copy(doc_comment)
            driver.press(opinion_el_xpath, "Control+V")
        # file_opinion_el = driver.locator( file_opinion_el_xpath)

        # # js_str = '()=>{document.querySelector("'+file_opinion_el_xpath+'").setAttribute("value","'+doc_comment +'")}'

    print("文件审查添加完成")
